# -*- encoding=utf8 -*-
"""
RedFlag-TC000095   （拍摄进入装饰页）剪辑转场功能
剪辑下载所有转场场景
"""
__author__ = "ldm"

import sys
import os
import yaml

# 获取当前脚本所在目录.py
current_dir = os.path.dirname(os.path.abspath(__file__))
# 获取上级目录.air
parent_dir = os.path.dirname(current_dir)
# 获取上级目录air
grandparent_dir = os.path.dirname(parent_dir)
# 获取和air目录平级的conf、testcase目录路径
conf_dir = os.path.join(grandparent_dir, 'conf')
testcase_dir = os.path.join(grandparent_dir, 'testcase')
# 将conf、testcase目录添加到sys.path
sys.path.append(conf_dir)
sys.path.append(testcase_dir)

from PageFunction import CameraVideoShooter
from elements import *

auto_setup(__file__)
shooter = CameraVideoShooter()

log("--------------------------------读取yaml文件--------------------------------------")


def read_yaml(file_path):
    """读取YAML文件数据"""
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            data = yaml.safe_load(file)
        return data
    except FileNotFoundError:
        print(f"文件 {file_path} 不存在")
        raise
    except yaml.YAMLError as e:
        print(f"解析YAML文件 {file_path} 出错: {str(e)}")
        raise


log("--------------------------------封装断言方法--------------------------------------")


def assert_download_success(shooter, transition_node, transition_name):
    """断言转场下载成功（失败时终止测试）"""
    parent_node = transition_node.parent()
    parent_children = parent_node.children()

    # 父节点无可用子节点 → 直接失败
    assert len(parent_children) > 0, f"断言失败：转场 {transition_name} 的父节点无可用子节点"

    first_child = parent_children[0]
    first_child_children = first_child.children()

    # 根据子节点数量判断是否已下载（根据实际UI调整）
    if len(first_child_children) < 2:
        child_count = shooter.get_child_count(first_child)
        assert child_count == 1, f"断言失败：转场 {transition_name} 下载后子节点数量应为1，实际为 {child_count}"
        print(f"转场 {transition_name} 下载验证成功")
        return

    # 等待加载进度条消失（超时则失败）
    loading_indicator = first_child.children()[2]  # 假设第三个子节点是进度条
    is_disappeared = shooter.wait_for_element_disappearance(loading_indicator, 20)
    assert is_disappeared, f"断言失败：转场 {transition_name} 加载进度条超时未消失"

    # 验证最终子节点数量
    final_child_count = shooter.get_child_count(first_child)
    assert final_child_count == 1, f"断言失败：转场 {transition_name} 下载后子节点数量应为1，实际为 {final_child_count}"
    print(f"转场 {transition_name} 下载验证成功")


log("--------------------------------封装转场点击逻辑--------------------------------------")


def click_all_transitions(shooter, data):
    """遍历转场数据执行下载（失败时终止测试）"""
    need_swipe_transitions = ["回忆", "推近"]

    for transition in data['transitions']:
        transition_name = transition['name']
        transition_text = transition['poco']['text']

        # 定位元素（元素不存在则直接失败）
        transition_element = shooter.get_element_by_text(transition_text)
        assert transition_element.exists(), f"未找到转场元素 {transition_text}（名称：{transition_name}）"

        # 点击并验证下载（断言失败时抛异常终止）
        shooter.click_element(transition_element)
        assert_download_success(shooter, transition_element, transition_name)  # 内部含断言，失败即终止

        # 特定转场滑动（滑动失败则终止）
        if transition_name in need_swipe_transitions:
            log(f"转场 {transition_name} 下载完成，执行横向滑动")
            swipe_success = shooter.swipe_screen((0.9, 0.8), (0.05, 0.8))  # 假设swipe_screen返回是否成功
            assert swipe_success, f"转场 {transition_name} 滑动操作失败"


log("--------------------------------用例执行主流程--------------------------------------")

# 前置操作：进入拍摄→装饰页→剪辑→转场页面
shooter.enter_photography_decoration_page()
shooter.click_element(edit_button)
sleep(2.0)
shooter.swipe_screen((0.8, 0.75), (0.45, 0.75))  # 拖动视频条
shooter.click_element(edit_segmentation)  # 点击分割
shooter.click_element(edit_division)  # 进入转场选择页

# 读取转场YAML文件
yaml_file_path = os.path.join(conf_dir, 'TC000095_clip_transition.yaml')
transition_data = read_yaml(yaml_file_path)

# 执行所有转场下载验证
log("-------------------------开始验证所有转场下载-------------------------")
click_all_transitions(shooter, transition_data)

# 清理操作：关闭应用
stop_app(UGC_package_name)
log("-------------------------转场下载测试完成-------------------------")






